package com.bbcare.nutritious.plat.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateTimeUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.PropertiesUtils;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.ToolUtils;
import com.bbcare.nutritious.plat.service.INutritionFoodService;
import com.bbcare.nutritious.plat.service.INutritionSchemeService;

/**
 *
 * @name:         AppNutritionUsedController.java
 * @author:       tao
 * @createTime:   2017年11月20日
 * @description:  app营养推送和上传
 * @modify:
 *
 */
@Controller
@RequestMapping("/webapi/service/appNutrition")
public class AppNutritionController {

    public static final Logger logger = Logger.getLogger(AppNutritionController.class);

    @Autowired
    private INutritionSchemeService nutritionScheme;
    @Autowired
    private INutritionFoodService nutritionFoodService;

    @ResponseBody
    @RequestMapping("/scheduleList")
    public ResultModel<Object> scheduleList(HttpServletRequest request, @RequestBody String jsonStr)
            throws Exception {
        logger.info("in scheduleList----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out patientScheduleQry----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，用户ID不能为空");
        }

        /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}

		Map<String,Object> rspMap = nutritionScheme.patientScheduleQry(requestParam);

        logger.debug("out scheduleList----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 根据分类id获取食物列表
     * @param request
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/listFoodByType")
    public ResultModel<Object> listFoodByType(HttpServletRequest request, @RequestBody String jsonStr)throws Exception {
        logger.info("in listFoodByType----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String typeId = requestParam.getString("typeId");
        if(StringUtils.isEmpty(typeId)){
        	logger.debug("out patientScheduleQry----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，用户ID不能为空");
        }

        /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}
		//计算分页参数
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("typeId", typeId);
		int curPage = requestParam.getInteger("curPage");
		int pageSize = requestParam.getInteger("pageSize");

		param.put("startNum", (curPage-1)*pageSize);
		param.put("pageSize", pageSize);

		Map<String,Object> rspMap = nutritionScheme.listFoodByType(param);

        logger.debug("out listFoodByType----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 添加当天的食物剂量(包括新增)
     * @param request
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("saveUserEatFoods")
    public ResultModel<Object> saveUserEatFoods(HttpServletRequest request, @RequestBody String jsonStr)
            throws Exception {
        logger.info("in saveUserEatFoods----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"用户id不能为空");
        }
        String time = DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd);
        requestParam.put("time", time);
        String foodId = requestParam.getString("foodId");
        String total = requestParam.getString("total");
        String periodId = requestParam.getString("periodId");//时间段id
        String situationId = requestParam.getString("situationId");//食谱id
        if(StringUtils.isEmpty(situationId) && (StringUtils.isEmpty(foodId) || StringUtils.isEmpty(total) || StringUtils.isEmpty(periodId))){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"食谱参数不正确");
        }
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}

        Map<String,Object> rspMap = nutritionScheme.patientScheduleUpload(requestParam);

        logger.debug("out saveUserEatFoods----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 添加食物
     */
    @ResponseBody
    @RequestMapping("foodModify")
    public ResultModel<Object> foodModify(HttpServletRequest request, @RequestBody String jsonStr)
            throws Exception {
        logger.info("in foodModify----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String foodName = requestParam.getString("foodName");
        if(StringUtils.isEmpty(foodName)){
        	logger.debug("out foodModify----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"食物名称不能为空");
        }

        String foodTypeId = requestParam.getString("foodTypeId");
        if(StringUtils.isEmpty(foodTypeId)){
        	logger.debug("out foodModify----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"食物类型不能为空");
        }

        String foodUnit = requestParam.getString("foodUnit");
        if(StringUtils.isEmpty(foodUnit)){
        	logger.debug("out foodModify----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"食物单位不能为空");
        }

        String foodLibraryId = requestParam.getString("foodLibraryId");
        if(StringUtils.isEmpty(foodLibraryId)){
        	logger.debug("out foodModify----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"食物库不能为空");
        }

        String nutrients = requestParam.getString("nutrients");
        if(StringUtils.isEmpty(nutrients)){
        	logger.debug("out foodModify----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"食物营养元素不能为空");
        }else{
        	JSONArray json = requestParam.getJSONArray("nutrients");
        	if(null == json || json.size() ==0){
        		logger.debug("out foodModify----arg== null");
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"食物营养元素不能为空");
        	}
        }

        requestParam.put("tenantId","tnbycfta001");
        requestParam.put("createAuthor","13tnbycfdoc001");

        Map<String,Object> rspMap = nutritionFoodService.foodModify(requestParam);

        logger.info("out foodTypeModify----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }

}
